import { defineStore } from 'pinia'
import axios from 'axios'
import { reactive } from 'vue'

const useQuestionStore = defineStore('question', () => {
    const state = reactive({
        qusetionList: [],    // 题目列表
        answerList: [],   // 答案
        num: 0,   // 记录当前是第几个题目
        totalScore: 0
    })

    // 仓库中的变量想要修改值一定要用仓库中定义的函数
    function getQuestionList() {  // 修改qusetionList
        // 获取题目
        axios.get('https://mock.mengxuegu.com/mock/6767738f98077b17fe6792e2/question-naire')
            .then(res => {
                state.qusetionList = res.data.questions
                console.log(state.qusetionList);
            })
    }

    function saveAnswerList(answer) {
        state.answerList.push(answer)
        console.log(state.answerList);
    }

    function addNum() {
        state.num++
    }

    // 计算得分
    function calculateTotalScore() {
        let num = 0;
        if (state.qusetionList.length && state.answerList.length) {
            console.log(state.answerList);
            state.qusetionList.forEach((question, index) => {
                question.topic_answer.forEach((answer) => {
                    if (answer.topic_answer_id === state.answerList[index]) {
                        num += answer.is_standard_answer;
                    }
                });
            });
        }
        state.totalScore = num * 20;  // 更新 totalScore
    }


    // 再来一次之后将answerList、totalScore、num重置
    const clear = () => {
        state.answerList = []
        state.totalScore = 0
        state.num = 0
    }

    return {
        state,
        getQuestionList,
        saveAnswerList,
        addNum,
        calculateTotalScore,
        clear
    }
})

export default useQuestionStore